import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import {
  getCostItemList,
  getCostItemDetail,
  addCostItem,
  updateCostItem,
  deleteCostItem,
  getCostItemTree
} from '../apis/costItem';

export const useCostItem = () => {
  // 加载状态
  const loading = ref(false);
  
  // 搜索表单
  const searchForm = reactive({
    itemName: '',
    itemCode: '',
    itemType: null,
    status: null
  });
  
  // 成本项目列表数据
  const costItemList = ref([]);
  
  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });
  
  // 成本项目类型选项
  const costItemTypes = ref([
    { label: '人力成本', value: 1 },
    { label: '物料成本', value: 2 },
    { label: '设备成本', value: 3 },
    { label: '行政费用', value: 4 },
    { label: '差旅费用', value: 5 },
    { label: '营销费用', value: 6 },
    { label: '研发费用', value: 7 },
    { label: '其他费用', value: 8 }
  ]);
  
  // 预算周期选项
  const budgetCycles = ref([
    { label: '月度', value: 1 },
    { label: '季度', value: 2 },
    { label: '年度', value: 3 }
  ]);
  
  // 查看对话框
  const viewDialogVisible = ref(false);
  const viewForm = reactive({});
  
  // 编辑对话框
  const editDialogVisible = ref(false);
  const editForm = reactive({
    id: '',
    itemCode: '',
    itemName: '',
    itemType: 1,
    parentId: 0,
    budgetCycle: 1,
    isLeaf: 1,
    status: 1,
    description: '',
    sortOrder: 0
  });
  const editLoading = ref(false);
  
  // 新增对话框
  const addDialogVisible = ref(false);
  const addForm = reactive({
    itemCode: '',
    itemName: '',
    itemType: 1,
    parentId: 0,
    budgetCycle: 1,
    isLeaf: 1,
    status: 1,
    description: '',
    sortOrder: 0
  });
  const addLoading = ref(false);
  
  // 格式化状态
  const formatStatus = (row) => {
    return row.status === 1 ? '启用' : '停用';
  };
  
  // 格式化成本类型
  const formatCostType = (row) => {
    const type = costItemTypes.value.find(t => t.value === row.itemType);
    return type ? type.label : '未知';
  };
  
  // 格式化预算周期
  const formatBudgetCycle = (row) => {
    const cycle = budgetCycles.value.find(c => c.value === row.budgetCycle);
    return cycle ? cycle.label : '未知';
  };
  
  // 格式化是否末级
  const formatIsLeaf = (row) => {
    return row.isLeaf === 1 ? '是' : '否';
  };
  
  // 加载成本项目列表
  const loadCostItems = async () => {
    loading.value = true;
    try {
      const params = {
        ...searchForm,
        page: pagination.currentPage,
        pageSize: pagination.pageSize
      };
      
      const response = await getCostItemList(params);
      if (response.code === 200) {
        // 从后端返回的data中获取records和total
        costItemList.value = response.data.records;
        pagination.total = response.data.total;
      } else {
        ElMessage.error(response.message || '获取数据失败');
      }
      
    } catch (error) {
      console.error('获取成本项目列表失败:', error);
      ElMessage.error('获取数据失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };
  
  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1;
    loadCostItems();
  };
  
  // 重置搜索
  const resetSearch = () => {
    Object.assign(searchForm, {
      itemName: '',
      itemCode: '',
      itemType: null,
      status: null
    });
    pagination.currentPage = 1;
    loadCostItems();
  };
  
  // 分页大小改变
  const handleSizeChange = (size) => {
    pagination.pageSize = size;
    loadCostItems();
  };
  
  // 页码改变
  const handleCurrentChange = (current) => {
    pagination.currentPage = current;
    loadCostItems();
  };
  

  
  // 查看详情
  const handleView = async (row) => {
    try {
      const response = await getCostItemDetail(row.id);
      if (response.code === 200) {
        // 使用后端返回的完整数据填充详情表单
        Object.assign(viewForm, response.data);
        viewDialogVisible.value = true;
      } else {
        ElMessage.error(response.message || '获取详情失败');
      }
    } catch (error) {
      console.error('获取成本项目详情失败:', error);
      ElMessage.error('获取详情失败，请稍后重试');
    }
  };
  
  // 编辑
  const handleEdit = (row) => {
    Object.assign(editForm, row);
    editDialogVisible.value = true;
  };
  
  // 打开新增对话框
  const handleAdd = () => {
    Object.assign(addForm, {
      itemCode: '',
      itemName: '',
      itemType: 1,
      parentId: 0,
      budgetCycle: 1,
      isLeaf: 1,
      status: 1,
      description: '',
      sortOrder: 0
    });
    addDialogVisible.value = true;
  };
  
  // 保存编辑
  const saveEdit = async () => {
    editLoading.value = true;
    try {
      const response = await updateCostItem(editForm.id, editForm);
      if (response.code === 200) {
        ElMessage.success('编辑成功');
        editDialogVisible.value = false;
        loadCostItems();
      } else {
        ElMessage.error(response.message || '编辑失败');
      }
    } catch (error) {
      console.error('编辑成本项目失败:', error);
      ElMessage.error('编辑失败，请稍后重试');
    } finally {
      editLoading.value = false;
    }
  };
  
  // 保存新增
  const saveAdd = async () => {
    addLoading.value = true;
    try {
      const response = await addCostItem(addForm);
      if (response.code === 200) {
        ElMessage.success('新增成功');
        addDialogVisible.value = false;
        loadCostItems();
      } else {
        ElMessage.error(response.message || '新增失败');
      }
    } catch (error) {
      console.error('新增成本项目失败:', error);
      ElMessage.error('新增失败，请稍后重试');
    } finally {
      addLoading.value = false;
    }
  };
  
  // 删除
  const handleDelete = async (id) => {
    loading.value = true;
    try {
      const response = await deleteCostItem(id);
      if (response.code === 200) {
        ElMessage.success('删除成功');
        loadCostItems();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除成本项目失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  };
  
  // 获取图表数据
  const getChartData = () => {
    // 模拟图表数据
    return {
      pieData: {
        labels: ['人力成本', '物料成本', '设备成本', '行政费用', '其他费用'],
        values: [35, 20, 15, 10, 20]
      },
      barData: {
        labels: ['人力成本', '物料成本', '设备成本', '行政费用', '差旅费用', '营销费用', '研发费用', '其他费用'],
        values: [15, 10, 8, 12, 7, 9, 11, 6]
      }
    };
  };
  
  return {
    loading,
    searchForm,
    costItemList,
    pagination,
    viewDialogVisible,
    viewForm,
    editDialogVisible,
    editForm,
    editLoading,
    addDialogVisible,
    addForm,
    addLoading,
    costItemTypes,
    budgetCycles,
    formatStatus,
    formatCostType,
    formatBudgetCycle,
    formatIsLeaf,
    loadCostItems,
    handleSearch,
    resetSearch,
    handleSizeChange,
    handleCurrentChange,
    handleEdit,
    handleDelete,
    handleView,
    saveEdit,
    handleAdd,
    saveAdd,
    getChartData
  };
};